//
//  SinaHomeComposeController.m
//  MySinaWeiboProjectForOC
//
//  Created by apple on 2016/11/24.
//  Copyright © 2016年 WangChen. All rights reserved.
//

#import "SinaHomeComposeController.h"
#import "UIBarButtonItem+extension.h"
#import "SinaUserAccountViewModel.h"
#import "SinaComposePictureController.h"
#import "UIButton+extension.h"
#import "UIImage+extension.h"
#import <SVProgressHUD.h>
#import "MyAFNTools.h"


@interface SinaHomeComposeController ()<UITextViewDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

//输入框
@property (nonatomic,weak) UITextView *textView;
//占位标签
@property (nonatomic,weak) UILabel *placeHolderLable;
//发布按钮
@property (nonatomic,weak) UIBarButtonItem *sendBtnItem;
//工具条
@property (nonatomic,weak) UIStackView *stackView;
//选中的图片
@property(nonatomic,strong) NSMutableArray<UIImage *> *imageArray;
//视图控制器
@property(nonatomic,strong) SinaComposePictureController *pictureVC;


@end

@implementation SinaHomeComposeController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setupUI];
}


#pragma mark
#pragma mark - 布置界面
-(void)setupUI{
    
    //设置标题
    [self setupTitle];
    
    //左上角返回按钮
    [self setupBackBtn];
    
    
    //右上角发布按钮
    [self setupsendBtn];
    
    //设置textView
    [self setupTextView];
    
    //添加图片视图
    [self setupPictureView];
    
    //底部工具条
    [self setupToolBar];
    
    //注册通知接收,在键盘弹出来时把工具条上移动
    [self registKeyboardNoti];
    
   
    
    
    
}


#pragma mark
#pragma mark - 添加图片视图
-(void)setupPictureView{
    
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    
    CGFloat itemW = (kScreenWidth - 4 * kMargin) / 3;
    
    layout.itemSize = CGSizeMake(itemW, itemW);
    
    layout.minimumLineSpacing = kMargin;
    layout.minimumInteritemSpacing = kMargin;
    layout.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    layout.sectionInset = UIEdgeInsetsMake(kMargin, kMargin, 0, kMargin);
    
    
    //创建collection
    SinaComposePictureController *pictureVC = [[SinaComposePictureController alloc]initWithCollectionViewLayout:layout];
    _pictureVC = pictureVC;
    pictureVC.collectionView.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1];
    pictureVC.imageArray = self.imageArray;
    
    __weak SinaHomeComposeController *weakSelf = self;
    pictureVC.btnDidClick = ^(){
        [weakSelf presentPickerVC];
    };
    
    
    [self.view addSubview: pictureVC.collectionView];
    [self addChildViewController:pictureVC];
    
    [pictureVC.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(kScreenHeight * 2.0 / 3.0);
    }];
    
}



#pragma mark
#pragma mark - 视图即将显示时
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    _pictureVC.collectionView.hidden = self.imageArray.count == 0;
}




#pragma mark
#pragma mark - 注册键盘消息通知
-(void)registKeyboardNoti{
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateToolBarWhenRecieveNotification:) name:UIKeyboardWillChangeFrameNotification object:nil];
}


#pragma mark
#pragma mark - 通知触发方法调整toolBar位置
-(void)updateToolBarWhenRecieveNotification:(NSNotification *)noti{
    NSDictionary *userInfo = noti.userInfo;
    CGRect newFrame = ((NSValue*)userInfo[@"UIKeyboardFrameEndUserInfoKey"]).CGRectValue;
    
    CGFloat newY = newFrame.origin.y - 667;
    
    [_stackView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.view).offset(newY);
    }];
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
    
}



#pragma mark
#pragma mark - 设置textView
-(void)setupTextView{
    
    UITextView *textView = [[UITextView alloc]init];
    _textView = textView;
    [self.view addSubview:textView];
    [textView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.top.equalTo(self.view);
        make.height.mas_equalTo(kScreenHeight / 3.0);
    }];
    
    textView.font = [UIFont systemFontOfSize:15];
    textView.textColor = [UIColor darkGrayColor];
    textView.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
    textView.delegate = self;
    
    //设置键盘
    textView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    textView.alwaysBounceVertical = YES;
 
    
    //占位文字用Lable实现
    UILabel *placeHolderLbl = [[UILabel alloc]init];
    placeHolderLbl.text = @"请在此输入微博内容";
    placeHolderLbl.textColor = [UIColor lightGrayColor];
    placeHolderLbl.font = [UIFont systemFontOfSize:15];
    [textView addSubview:placeHolderLbl];
    
    [placeHolderLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(textView).offset(8);
        make.leading.equalTo(textView).offset(5);
    }];
    _placeHolderLable = placeHolderLbl;
}



#pragma mark
#pragma mark - 设置标题
-(void)setupTitle{
    NSString *userName = [SinaUserAccountViewModel shared].userAccountModel.name;
    NSString *titleStr;
    
    UILabel *titleLable = [[UILabel alloc]init];
    titleLable.numberOfLines = 0;
    titleLable.font = [UIFont systemFontOfSize:16];
    titleLable.textColor = [UIColor grayColor];
    
    if(userName){
        titleStr = [NSString stringWithFormat:@"发布微博\n%@",userName];
        NSMutableAttributedString *attString = [[NSMutableAttributedString alloc]initWithString:titleStr];
        NSRange range = [titleStr rangeOfString:userName];
        [attString addAttributes:@{NSForegroundColorAttributeName:[UIColor orangeColor],NSFontAttributeName:[UIFont systemFontOfSize:12]} range:range];
        titleLable.attributedText = attString;
    }else{
        titleStr = @"发布微博";
        titleLable.text = titleStr;
    }
    [titleLable sizeToFit];
    titleLable.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLable;
}


#pragma mark
#pragma mark - 加载底部工具条
-(void)setupToolBar{
    
    UIStackView *stackView = [[UIStackView alloc]init];
    stackView.axis = UILayoutConstraintAxisHorizontal;
    stackView.distribution = UIStackViewDistributionFillEqually;
    [self.view addSubview:stackView];
    _stackView = stackView;
    
    [stackView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    
    //_highlighted
    NSArray<NSString*> *imageNameArray = @[@"compose_camerabutton_background",@"compose_emoticonbutton_background",@"compose_keyboardbutton_background",@"compose_mentionbutton_background",@"compose_toolbar_picture"];
    
    for (int i = 0; i < 5; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setImage:[UIImage imageNamed:imageNameArray[i]] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_highlighted",imageNameArray[i]]] forState:UIControlStateHighlighted];
        [btn sizeToFit];
        
        btn.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
        
        btn.tag = i + 10000;
        [btn addTarget:self action:@selector(toolBarDidClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [stackView addArrangedSubview:btn];
    }
    
    
}


#pragma mark
#pragma mark - 底部工具条点击触发方法
-(void)toolBarDidClick:(UIButton *)sender{
    
    NSInteger btnTag = sender.tag;
    
    switch (btnTag) {
        case 10000:
            NSLog(@"点击了相机");
            break;
        case 10001:
            NSLog(@"点击了表情");
            break;
        case 10002:
            NSLog(@"点击了键盘");
            break;
        case 10003:
            NSLog(@"点击了@");
            break;
        case 10004:
        {
           
            [self presentPickerVC];
        }
            break;
            
        default:
            break;
    }
    
}



#pragma mark
#pragma mark - 弹出pickerView的方法
-(void)presentPickerVC{
    
    UIImagePickerController *pickerVC = [[UIImagePickerController alloc]init];
    pickerVC.view.backgroundColor = [UIColor whiteColor];
    pickerVC.delegate = self;
    
    [self presentViewController:pickerVC animated:YES completion:nil];
}



#pragma mark
#pragma mark - 左上角返回按钮
-(void)setupBackBtn{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc]initWithTitle:@"返回" image:@"navigationbar_back_withtext" addTarget:self action:@selector(backBtnDidClick)];
    
    self.navigationItem.leftBarButtonItem = backItem;
}


#pragma mark
#pragma mark - 右上角发布
-(void)setupsendBtn{
    //common_button_orange_highlighted
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:@"  发布  " forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"common_button_orange_highlighted"] forState:UIControlStateHighlighted];
    [btn setBackgroundImage:[UIImage imageNamed:@"common_button_orange"] forState:UIControlStateNormal];
    [btn setBackgroundImage:[UIImage imageNamed:@"common_button_white_disable"] forState:UIControlStateDisabled];
    btn.titleLabel.font = [UIFont systemFontOfSize:18];
    [btn sizeToFit];
    
    [btn addTarget:self action:@selector(sendBtnDidClick) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *sendBtnItem = [[UIBarButtonItem alloc]init];
    sendBtnItem.customView = btn;
    sendBtnItem.enabled = NO;
    
    self.navigationItem.rightBarButtonItem = sendBtnItem;
    self.sendBtnItem = sendBtnItem;
}


#pragma mark
#pragma mark - 返回按钮监听
-(void)backBtnDidClick{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark
#pragma mark - 发布按钮监听
-(void)sendBtnDidClick{
    NSString *usertoken = [SinaUserAccountViewModel shared].userAccountModel.access_token;
    
    NSDictionary *parameters = @{@"access_token" : usertoken, @"status" : _textView.text};
    
    __weak SinaHomeComposeController *weakSelf = self;
    if(self.imageArray.count == 0){
        
        
        [[MyAFNTools sharedOwnTool] requestWithURLStr:updateMessage method:POST paramter:parameters complete:^(id responseObj, NSError *error) {
            
            if(error){
                NSLog(@"%@",error);
                [SVProgressHUD showErrorWithStatus:@"发布失败了~~~~(>_<)~~~~"];
                return;
            }
            
            [SVProgressHUD showSuccessWithStatus:@"发布成功了😆"];
            [weakSelf dismissViewControllerAnimated:YES completion:^{
                [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationRefreshHomePage object:nil];
            }];
        }];
        return;
    }
    
    UIImage *image = self.imageArray.firstObject;
    NSData *imageData = UIImagePNGRepresentation(image);
    //pic
    [[MyAFNTools sharedOwnTool] POST:uploadMessage parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        [formData appendPartWithFileData:imageData name:@"pic" fileName:@"sasasa" mimeType:@"application/octet-stream"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [SVProgressHUD showSuccessWithStatus:@"图片微博发布成功了😆"];
        [weakSelf dismissViewControllerAnimated:YES completion:^{
            [[NSNotificationCenter defaultCenter]postNotificationName:kNotificationRefreshHomePage object:nil];
        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
        [SVProgressHUD showErrorWithStatus:@"图片微博发布失败了~~~~(>_<)~~~~"];
    }];
    
    
}


#pragma mark
#pragma mark - textView内容改变时触发代理方法
-(void)textViewDidChange:(UITextView *)textView{
    self.placeHolderLable.hidden = textView.text.length != 0;
    self.sendBtnItem.enabled = textView.text.length != 0;
}



#pragma mark
#pragma mark - imageArray get方法
-(NSMutableArray<UIImage *> *)imageArray{
    if(!_imageArray){
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}


#pragma mark
#pragma mark - UIimagePickerViewController 代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
    //UIImagePickerControllerOriginalImage
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    UIImage *newImage = [image scaleImageWithWidth:kScreenWidth - 2 * kMargin];
    [self.imageArray addObject:newImage];
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    [self.pictureVC.collectionView reloadData];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}






- (void)dealloc
{
    NSLog(@"释放覅了 composeVC");
}


@end
